module RailsEnhancer
  module Controller
    class Base
      def initialize(controller_inst)
        @__controller_inst = controller_inst
        set_instance_vars(@__controller_inst.instance_variables.select { |e| !e.to_s.start_with?("@_") })
      end

      def call
        before_action
        action
        after_action
      end

      def before_action
      end

      def action
        raise NotImplementedError
      end

      def after_action
        port_instance_vars
      end

      def method_missing(method_sym, *arguments, &block)
        @__controller_inst.send(method_sym, *arguments, &block)
      end

      private

      def set_instance_vars(var_names)
        var_names.each do |var_name|
          instance_variable_set(var_name, @__controller_inst.instance_variable_get(var_name))
        end
      end

      def port_instance_vars
        (instance_variables-[:@controller_inst]).each do |e|
          val = instance_variable_get(e)
          @__controller_inst.instance_variable_set(e, val)
        end
      end
    end
  end
end
